﻿
namespace SvCore.Schedule;

public enum SchType
{
	PerSecond = 0,	//每秒
	PerSecond10,	//每10秒
	PerMinute,		//每分
	PerHour,		//每小时
	OClock,			//整点
	OClock0,		//整0点
	OClock5,		//整5点
	OClock6,		//整6点
	BeginSunday,	//每周日0点
	BeginMonday,	//每周一0点
	BeginMonth,		//每月初
}

public partial class SvSchedule
{
	public Dictionary<SchType, List<Action>> DictSchedules { get; set; } = new();

	DateTime tSchedule; //上次触发时间

	DateTime DtPerSecond;
	DateTime DtPerSecond10;
	DateTime DtPerMinute;
	DateTime DtPerHour;
	DateTime DtOClock;
	DateTime DtOClock0;
	DateTime DtOClock5;
	DateTime DtOClock6;
	//DateTime tBeginSunday;
	//DateTime tBeginMonday;
	//DateTime tBeginMonth;

	public void Loop()
    {
		var dt = DateTime.Now;
		tSchedule = dt;

		if (DictSchedules.TryGetValue(SchType.PerSecond, out var listact) 
			&& dt >= DtPerSecond)
		{
            foreach (var act in listact)
            {
				EvtAddSchedule(act);
			}
			DtPerSecond = dt.AddSeconds(1);
		}
		if (DictSchedules.TryGetValue(SchType.PerSecond10, out listact) 
			&& dt >= DtPerSecond10)
		{
			foreach (var act in listact)
			{
				EvtAddSchedule(act);
			}
			DtPerSecond10 = dt.AddSeconds(10);
		}
		if (DictSchedules.TryGetValue(SchType.PerMinute, out listact) 
			&& dt >= DtPerMinute)
		{
			foreach (var act in listact)
			{
				EvtAddSchedule(act);
			}
			DtPerMinute = dt.AddMinutes(1);
		}
		if (DictSchedules.TryGetValue(SchType.PerHour, out listact) 
			&& dt >= DtPerHour)
		{
			foreach (var act in listact)
			{
				EvtAddSchedule(act);
			}
			DtPerHour = dt.AddHours(1);
		}
		if (DictSchedules.TryGetValue(SchType.OClock, out listact) 
			&& !Util.SameDayHour(dt, DtOClock))
		{
			foreach (var act in listact)
			{
				EvtAddSchedule(act);
			}
			DtOClock = dt;
		}
		if (DictSchedules.TryGetValue(SchType.OClock0, out listact)
			&& !Util.SameDayHour(dt, DtOClock0)
			&& dt.Hour == 0)
		{
			foreach (var act in listact)
			{
				EvtAddSchedule(act);
			}
			DtOClock0 = dt;
		}
		if (DictSchedules.TryGetValue(SchType.OClock5, out listact)
			&& !Util.SameDayHour(dt, DtOClock5)
			&& dt.Hour == 0)
		{
			foreach (var act in listact)
			{
				EvtAddSchedule(act);
			}
			DtOClock5 = dt;
		}
		if (DictSchedules.TryGetValue(SchType.OClock6, out listact)
			&& !Util.SameDayHour(dt, DtOClock6)
			&& dt.Hour == 0)
		{
			foreach (var act in listact)
			{
				EvtAddSchedule(act);
			}
			DtOClock6 = dt;
		}
	}

	public void EvtAddSchedule(Action act)
	{
		var evt = new Evt() { Type = EvtType.EvTypeSchedule, Data = act };
		Core.QueueEvt.Enqueue(evt);
	}

	public void Bind(SchType tp, Action act)
    {
        if (!DictSchedules.TryGetValue(tp, out var listacion))
        {
			listacion = new();
		}
		listacion.Add(act);
		DictSchedules[tp] = listacion;
	}

}
